Ext.ns('journal.home');

journal.home.SearchTab = Ext.extend(Ext.Panel, (function() {

    var searchMask = null;
    var MSG_NORECORD = 'No match found';

    var loadEntry = function(treePath) {
        journal.StateService.restoreFlag = false;
        var tree = Ext.getCmp(journal.Constant.Id.ENTRY_TREE);
        tree.expandPath(treePath, 'id', function(a, targetNode) {
            if (!targetNode.isLeaf()) {
                Ext.Msg.show({
                    icon : Ext.MessageBox.ERROR,
                    buttons : Ext.Msg.OK,
                    title : MSG_NORECORD,
                    autoHeight : true,
                    autoWidth : true,
                    msg : 'The entry you are opening may have already been deleted.'
                });
            } else {
                journal.home.Main.editorPanel.newTabHandler(targetNode);
                journal.home.MainHandler.addRecentFileItem(targetNode);
                journal.StateService.add(journal.StateService.ST_TAB, targetNode.getPath());
                journal.StateService.add(journal.StateService.ST_TABORDER, targetNode.getPath());
            }
        });
    };

    var searchViewHandler = function(scope, checkbox, checked) {
        scope.get(0).setVisible(!checked);
        scope.get(1).setVisible(checked);
        if (!checked && scope.store.totalLength == 0) {//summary mode.                                    
            var dataView = Ext.getCmp(journal.home.SearchTab.ID_RES_SUMMARY);
            dataView.refresh();
        }
    };

    return {

        constructor : function(config) {
            config = config || {};
            config.listeners = config.listeners || {};
            this.store = config.store;
            journal.home.SearchTab.superclass.constructor.call(this, config);
        },
        initComponent : function() {

            this.resultTpl = new Ext.XTemplate('<tpl for=".">', '<div class="search-item">',
                    '<h3><span>{lastUpdate:date("M j, Y h:i:s A")} <br/></span>',
                    '<a class="searchItemLink" jrnl:treePath="{treePath}" jrnl:nodeId="l-{entryId}">{title}</a> </h3>',
                    '<p>{summary}</p>', '</div></tpl>');

            var logger = journal.LoggerFactory.getLogger("journal.home.SearchTab");
            logger.debug(this);

            var summaryView = new Ext.DataView({
                id : journal.home.SearchTab.ID_RES_SUMMARY,
                tpl : this.resultTpl,
                store : this.store,
                itemSelector : 'div.search-item',
                loadingText : 'Searching...',
                emptyText : '<div class=search-item>' + MSG_NORECORD + '</div>'
            });

            var gridView = new Ext.grid.GridPanel({
                id : journal.home.SearchTab.ID_RES_GRID,
                store : this.store,
                autoExpandColumn : 'summary',
                columns : [ {
                    header : "Title",
                    width : 50,
                    dataIndex : 'title',
                    sortable : true
                }, {
                    header : "Summary",
                    dataIndex : 'summary'
                }, {
                    header : "Last Update",
                    width : 50,
                    dataIndex : 'lastUpdate',
                    sortable : true,
                    renderer : Ext.util.Format.dateRenderer('M j, Y h:i:s A'),
                } ],
                sm : new Ext.grid.RowSelectionModel({
                    singleSelect : true
                }),
                viewConfig : {
                    forceFit : true,
                    emptyText : MSG_NORECORD,
                    deferEmptyText : false
                },
                split : true,
                autoHeight : true,
                listeners : {
                    'celldblclick' : function(grid, row, col, event) {
                        var record = grid.getStore().getAt(row); // Get the Record
                        var treePath = record.get('treePath');
                        loadEntry(treePath);
                    }
                }
            });

            var searchToolbar = {
                items : [ {
                    xtype : 'radiogroup',
                    defaults : [ {
                        width : 'auto'
                    } ],
                    items : [ {
                        boxLabel : 'Summary',
                        name : 'rb-auto',
                        inputValue : 'summary',
                        width : 130
                    }, {
                        boxLabel : 'Grid',
                        name : 'rb-auto',
                        inputValue : 'grid',
                        checked : true,
                        handler : function(checkbox, checked) {
                            searchViewHandler(this, checkbox, checked);
                        }.createDelegate(this)
                    } ]
                } ]
            };

            var config = {
                id : 'search-tab-singleton',
                baseCls : 'search-results',
                iconCls : 'icon-search',
                items : [ new Ext.Panel({
                    items : [ summaryView ],
                    hidden : true
                }), new Ext.Panel({
                    items : [ gridView ]
                }) ],
                closable : true,
                autoScroll : true,
                tbar : searchToolbar,
                bbar : new Ext.PagingToolbar({
                    store : this.store,
                    pageSize : 20,
                    displayInfo : true,
                    displayMsg : 'Topics {0} - {1} of {2}',
                    emptyMsg : "No topics to display"
                })
            };

            //Event Handlers
            this.store.on('load', function() {
                searchMask.hide();
                gridView.view.refresh.defer(1000, null, gridView.view);
            });

            this.store.on('beforeload', function() {
                if (searchMask == null && this.getEl() != null) {
                    searchMask = new Ext.LoadMask(this.getEl().dom, {
                        msg : 'Searching, please wait...'
                    });
                }

                if (searchMask != null) {
                    searchMask.show();
                }

            }.createDelegate(this));

            // apply config
            Ext.apply(this, Ext.apply(this.initialConfig, config));

            // call parent
            journal.home.SearchTab.superclass.initComponent.apply(this, arguments);
        }

        ,
        initEvents : function() {
            journal.home.SearchTab.superclass.initEvents.call(this);
            this.body.on('click', this.onClick, this);
        },

        onClick : function(e, target) {
            if (target = e.getTarget('a:not(.exi)', 3)) {
                var nodeId = Ext.fly(target).getAttributeNS('jrnl', 'nodeId');
                var treePath = Ext.fly(target).getAttributeNS('jrnl', 'treePath');
                e.stopEvent();
                if (nodeId) {
                    loadEntry(treePath);
                }
            }
        },
    };
})());

journal.home.SearchTab.ID_RES_SUMMARY = 'result-summary';
journal.home.SearchTab.ID_RES_GRID = 'result-grid';

//register xtype
Ext.reg('journal.home.SearchTab', journal.home.SearchTab);